package cn.itcast.Rainbow_self_mention.Server;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetSocketAddress;
import java.util.Timer;
import java.util.TimerTask;

import cn.itcast.Rainbow_self_mention.Activity.Login;
import cn.itcast.Rainbow_self_mention.Activity.Personal;
import cn.itcast.Rainbow_self_mention.Activity.Regist;
import cn.itcast.Rainbow_self_mention.Activity.ResetPassword;
import cn.itcast.Rainbow_self_mention.Dao.SqlHelper;
import cn.itcast.Rainbow_self_mention.Tools.imfor;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class CountServer extends Service {
    @Nullable
    SqlHelper hp = new SqlHelper(this);
    Channel ch;
    String ip = imfor.ip;
    int port = 9528;
    Boolean link = false;
    private Timer timer;
    Handler Rhandler = Regist.handler;
    Handler Phandler = Personal.handler;
    Handler Lhandler = Login.handler;
    Handler Resethandler= ResetPassword.handler;

    /*
     *
     * Cop=1登录
     * Cop=2注册
     * Cop=3退出登录
     * Cop=4重置密码
     *
     * 34代表网络连接成功
     *
     * 11代表登陆成功
     * 12代表登录失败
     * 13代表已在别处登录
     *
     * 21注册成功
     * 22注册失败
     * 23已存在账户，注册失败
     *
     * 31退出成功
     * 32退出失败
     *
     *
     * 41密码重置成功
     * 42密码重置失败
     * 43用户不存在，密码重置失败
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new sender();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        connect();
    }

    public void addTimer() {
        if (timer == null) {
            timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    Bundle bundle = new Bundle();
                    Message login = Lhandler.obtainMessage();
                    Message regist = Rhandler.obtainMessage();
                    Message exist = Phandler.obtainMessage();
                    Message reset = Resethandler.obtainMessage();
                    if (link) {
                        bundle.putString("sentresult", "网络连接成功");
                    } else {
                        bundle.putString("sentresult", "网络连接错误");
                    }
                    login.setData(bundle);
                    regist.setData(bundle);
                    exist.setData(bundle);
                    reset.setData(bundle);
                    Lhandler.sendMessage(login);
                    Rhandler.sendMessage(regist);
                    Phandler.sendMessage(exist);
                    Resethandler.sendMessage(reset);

                }
            };
            timer.schedule(task, 5, 500);
        }
    }

    private void connect() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture bs = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast("input", new ChannelInboundHandlerAdapter() {
                            public void channelActive(ChannelHandlerContext ctx) {
                                link = true;

                                addTimer();
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                super.channelRead(ctx, msg);
                                operation(msg);
                            }

                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                ctx.fireChannelInactive();
                                link = false;
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress(ip, port));
        ch = bs.channel();

    }

    public class sender extends Binder {
        public void relink() {
            connect();
        }

        //登录
        public void Login(String account, String password) {
            String msg = "{" +
                    "\"Cop\":" + "\"1\"," +
                    "\"account\":" + "\"" + account + "\"," +
                    "\"password\":" + "\"" + password + "\"" +
                    "}" + '\n';
            ch.writeAndFlush(msg);
        }

        //注册
        public void Regist(String name, String phone, String identity, String password) {
            String msg = "{" +
                    "\"Cop\":" + "\"2\"," +
                    "\"name\":" + "\"" + name + "\"," +
                    "\"phone\":" + "\"" + phone + "\"," +
                    "\"identity\":" + "\"" + identity + "\"," +
                    "\"password\":" + "\"" + password + "\"" +
                    "}" + '\n';
            ch.writeAndFlush(msg);
        }

        //退出登录
        public void Exist(int userid) {
            String msg = "{" +
                    "\"Cop\":" + "\"3\"," +
                    "\"userid\":" + "\"" + userid + "\"" +
                    "}" + '\n';
            ch.writeAndFlush(msg);
        }
        //重置密码
        public void Reset( String phone, String identity, String password) {
            String msg = "{" +
                    "\"Cop\":" + "\"4\"," +
                    "\"phone\":" + "\"" + phone + "\"," +
                    "\"identity\":" + "\"" + identity + "\"," +
                    "\"password\":" + "\"" + password + "\"" +
                    "}" + '\n';
            ch.writeAndFlush(msg);
        }

    }

    public void operation(Object msg) throws JSONException {
        String m = msg.toString();
        JSONObject jsonObject = new JSONObject(m);
        //登录成功
        if (jsonObject.getString("Cop").equals("11")) {
            ContentValues values = new ContentValues();
            SQLiteDatabase db = hp.getWritableDatabase();
            String name = jsonObject.getString("name");
            String userphone = jsonObject.getString("mobile");
            int userid = jsonObject.getInt("user_id");
            values.put("username", name);
            values.put("userphone", userphone);
            values.put("userid", userid);
            db.update("logined", values, "_id=?", new String[]{1 + ""});
            db.close();
            Message login = Lhandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "登录成功");
            //bundle.putString("data", m);
            login.setData(bundle);
            Lhandler.sendMessage(login);
        }
        //登录失败
        if (jsonObject.getString("Cop").equals("12")) {
            Message login = Lhandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "登录失败");
            login.setData(bundle);
            Lhandler.sendMessage(login);
        }
        //已在别处登录
        if (jsonObject.getString("Cop").equals("13")) {
            Message login = Lhandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "已在别处登录");
            login.setData(bundle);
            Lhandler.sendMessage(login);
        }
        //网络连接成功
        if (jsonObject.getString("Cop").equals("34")) {
            link = true;
        }
        //注册成功
        if (jsonObject.getString("Cop").equals("21")) {
            Message regist = Rhandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "注册成功");
            regist.setData(bundle);
            Rhandler.sendMessage(regist);
        }
        //注册失败
        if (jsonObject.getString("Cop").equals("22")) {
            Message regist = Rhandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "注册失败");
            regist.setData(bundle);
            Rhandler.sendMessage(regist);
        }
        //已存在用户
        if (jsonObject.getString("Cop").equals("23")) {
            Message regist = Rhandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "已存在账户");
            regist.setData(bundle);
            Rhandler.sendMessage(regist);
        }
        //账号退出成功
        if (jsonObject.getString("Cop").equals("31")) {
            ContentValues values = new ContentValues();
            SQLiteDatabase db = hp.getWritableDatabase();
            values.put("username", "null");
            values.put("userphone", "null");
            values.put("userid", 0);
            db.update("logined", values, "_id=?", new String[]{1 + ""});
            db.delete("HISTORY", "_id!=?", new String[]{"1"});
            db.close();
            Message exist = Phandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "退出成功");
            exist.setData(bundle);
            Phandler.sendMessage(exist);
        }
        //账号退出失败
        if (jsonObject.getString("Cop").equals("32")) {
            Message exist = Phandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "退出失败");
            exist.setData(bundle);
            Phandler.sendMessage(exist);
        }
        //密码修改成功
        if (jsonObject.getString("Cop").equals("41")) {
            Message reset = Resethandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "修改成功");
            reset.setData(bundle);
            Resethandler.sendMessage(reset);
        }
        //密码修改失败
        if (jsonObject.getString("Cop").equals("42")) {
            Message reset = Resethandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "修改失败");
            reset.setData(bundle);
            Resethandler.sendMessage(reset);
        }
        //密码修改用户不存在
        if (jsonObject.getString("Cop").equals("43")) {
            Message reset = Resethandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "用户不存在");
            reset.setData(bundle);
            Resethandler.sendMessage(reset);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        ChannelFuture cf = ch.closeFuture();
        try {
            cf.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
